import axios from 'axios';
import moment from 'moment';

// 1. 初始状态.
const state = () => ({
    events: [],
    dependencies: [],
    build: [
        {
            key: 1,
            name: 'Group ID',
            value: '',
        },
        {
            key: 2,
            name: 'Artifact ID',
            value: '',
        },
        {
            key: 3,
            name: 'Version',
            value: '',
        },
    ],
    git: [
        {
            key: 1,
            name: 'Repository',
            value: '',
        },
        {
            key: 2,
            name: 'Branch',
            value: '',
        },
        {
            key: 3,
            name: 'Commit',
            value: '',
        },
        {
            key: 4,
            name: 'ID',
            value: '',
        },
        {
            key: 5,
            name: 'Time',
            value: '',
        },
    ],
    db: [
        {
            key: 1,
            name: 'Status',
            value: '',
        },
        {
            key: 2,
            name: 'DATABASE',
            value: '',
        },
    ],
    disk: [
        {
            key: 1,
            name: 'Status',
            value: '',
        },
    ],
});

// 2. 计算属性.
const getters = {};

// 3. 异步修改.
const actions = {
    loadInfo({ state }, iid) {
        axios.all([
            axios.get(`/info/${iid}`),
            axios.get(`/health/${iid}`),
            axios.get(`/dependencies/${iid}`),
            axios.get(`/instanceEvent?instanceId=${iid}`),
        ]).then(axios.spread((info, health, dependencies, events) => {
            state.build[0].value = info.data.build.group || '';
            state.build[1].value = info.data.build.artifact || '';
            state.build[2].value = info.data.build.version || '';

            state.git[0].value = info.data.git.remote.origin.url.slice(0, 47) || '';
            state.git[1].value = info.data.git.branch || '';
            state.git[2].value = info.data.git.commit.id.abbrev || '';
            state.git[3].value = info.data.git.commit.user.email || '';
            state.git[4].value = info.data.git.commit.time || '';

            state.db[0].value = health.data.components.db.status;
            state.db[1].value = health.data.components.db.details.database;
            state.disk[0].value = health.data.components.diskSpace.status || 'Unknown';

            state.dependencies = dependencies.data.slice(0, 12);
            state.events = events.data.slice(0, 7).map((item) => {
                const { id, eventDescription, createTime } = item;

                return {
                    id,
                    eventDescription,
                    createTime: moment(createTime * 1000).format('YYYY-MM-DD HH:mm:ss'),
                };
            });
        }));
    },
};

// 4. 同步修改.
const mutations = {
};

// 5. 模块导出.
export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
};
